window.onload = function() {
    var r = 30
    var down = new Array()
    var maxX = document.body.offsetWidth
    var maxY = document.body.offsetHeight
    var ds = document.querySelectorAll('div')
    var num = ds.length


    for (var i = 0; i < num; i++) {
        var x = {
            x: getRandomNumber(0, maxX - r),
            y: getRandomNumber(0, maxY - r),
            r: r,
            vX: getRandomNumber(Math.random(), Math.random() * 8),
            vY: getRandomNumber(Math.random(), Math.random() * 8),
            color: getRandomColor(),
        }
        down.push(x)
    }

    function getRandomColor() {
        var m = Math.floor(Math.random() * 10)
        if (m <= 2) {
            return 'red'
        }
        if (m <= 4) {
            return 'blue'
        }
        if (m <= 6) {
            return 'yellow'
        }
        if (m <= 8) {
            return 'green'
        }
        if (m <= 10) {
            return 'gray'
        }
        if (m <= 1) {
            return 'darkmagenta'
        }
    }
    draw()

    function draw() {

        for (i in down) {
            var x = i
            down[i].x += down[i].vX
            down[i].y += down[i].vY

            if (down[i].x >= maxX - r * 2) {
                down[i].x = maxX - r * 2
                down[i].vX = -down[i].vX
            }
            if (down[i].x <= 0) {
                down[i].x = 0
                down[i].vX = -down[i].vX
            }
            if (down[i].y >= maxY - r * 2) {
                down[i].y = maxY - r * 2
                down[i].vY = -down[i].vY
            }
            if (down[i].y <= 0) {
                down[i].y = 0
                down[i].vY = -down[i].vY
            }
            for (var j = 0; j < num; j++) {
                if (j !== x) {
                    if (Math.round(Math.pow(down[x].x - down[j].x, 2) +
                            Math.pow(down[x].y - down[j].y, 2)) <=
                        Math.round(Math.pow(r + r / 2, 2))) {
                        var tempX = down[x].vX
                        var tempY = down[x].vY
                        down[x].vX = down[j].vX
                        down[j].vX = tempX
                        down[x].vY = down[j].vY
                        down[j].vY = tempY
                    }
                }
            }
            ds[x].style.position = 'absolute'
            ds[x].style.left = down[i].x
            ds[x].style.top = down[i].y
            ds[x].style.width = down[i].r * 2
            ds[x].style.height = down[i].r * 2
            ds[x].style.backgroundColor = down[i].color
            ds[x].style.borderRadius = '50%'
        }
        setTimeout(function() {
            draw()
        }, 1);
    }



    function getRandomNumber(min, max) {
        return (min + Math.floor(Math.random() * (max - min)))
    }
}